package com.my.controller;

import cn.hutool.core.util.StrUtil;
import com.my.pojo.Branch;
import com.my.service.BranchService;
import com.my.service.impl.BranchServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/branchServlet")
public class BranchServlet extends HttpServlet {

    BranchService branchService = new BranchServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String branchId = req.getParameter("branchId");
        if(StrUtil.isNotEmpty(branchId)){
            Integer id = Integer.parseInt(branchId);
            Branch branch = branchService.getBranchById(id);
            req.setAttribute("branch",branch);
            req.getRequestDispatcher("branch/addBranch.jsp").forward(req,resp);
        }else {
            List<Branch> branchList = branchService.getBranchBy(Branch.builder().build());
            req.setAttribute("branchList",branchList);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String branchName = req.getParameter("branchName");
        String remark = req.getParameter("remark");
        Branch branch = Branch.builder().branchName(branchName).remark(remark).build();
        if(!branchService.isExist(branch)){
            branchService.addBranch(branch);
        }
        resp.sendRedirect("branch/branchList.jsp");
    }
}
